const fs = require('fs')

exports.meta = async (ctx) => {
  const {
    service_name
  } = ctx.request.params

  const data = require('./xds-api.json')
  if (!data[service_name]) {
    ctx.response.status = 404
    ctx.body = { success: false, message: "unfound." }
  }

  ctx.body = {
    success: true,
    data: {
      ...data[service_name]
    }
  }
}

exports.rows = async (ctx) => {
  const {
    service_name
  } = ctx.request.params

  const data = require('./xds-api.json')
  if (!data[service_name]) {
    ctx.response.status = 404
    ctx.body = { success: false, message: "unfound." }
  }

  ctx.body = {
    success: true,
    data: {
      meta: {
        ...data[service_name]
      },
      result: []
    }
  }
}

exports.create = async (ctx) => {
  const {
    appName,
    service_name,
    input_metas = [],
    output_metas = [],
  } = ctx.request.body

  const data = require('./xds-api.json')

  if (!service_name) {
    return "service_name is null"
  }

  if (data[service_name]) {
    return "service_name is repeat"
  }

  data[service_name] = { appName, input_metas, output_metas }

  fs.writeFileSync('./xds-api.json', JSON.stringify(data))

  ctx.body = {
    success: true
  }

}

exports.getApiList = async (ctx) => {
  const data = require('./xds-api.json')

  ctx.body = {
    success: true,
    data: Object.keys(data)
  }
}
